<template>
  <sub-page>
    <div class="award-setting-contaienr">
      <main-card>
        <card-top-info title="歌手设置"></card-top-info>
        <div class="award-info-list-container">
          <my-table style="height: auto">
            <el-table :data="singerList" highlight-current-row style="width: 100%" header-row-class-name="table-header">
              <el-table-column type="index" width="120" align="center" header-align="center" label="序号"> </el-table-column>
              <el-table-column min-width="120" align="center" header-align="center" label="歌手照片">
                <template slot-scope="scope">
                  <div class="upload-img">
                    <img width="47" height="31" style="border-radius: 4px" :src="scope.row.avator" alt="" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column min-width="100" label="歌手姓名" prop="name" align="center" header-align="center"> </el-table-column>
              <el-table-column label="微信绑定" align="center" min-width="120">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.singer_openId" type="success">已绑定</el-tag>
                  <el-tag v-else type="info">未绑定</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="歌手状态" align="center" min-width="120">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.kind"
                    active-value="1"
                    inactive-value="0"
                    @change="handleSingerStatusChange(scope.row)"
                  >
                  </el-switch>
                  <span style="margin-left: 8px;">{{ scope.row.kind === '1' ? '休息' : '不休息' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="200" align="center" header-align="center">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditSingerDialog(scope.row)">编辑</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="confirmDelateOpen(scope.row.awardid)">删除</el-button>
                  <el-button
                    v-if="!scope.row.singer_openId"
                    size="mini"
                    type="success"
                    @click="showBindWxDialog(scope.row)">
                    绑定
                  </el-button>
                  <el-button
                    v-else
                    size="mini"
                    type="warning"
                    @click="confirmUnbindWx(scope.row)">
                    解绑
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </my-table>
          <!-- 新增奖项按钮 -->
          <div class="addAwardBtn" @click="showAddSingerDialog"><span class="el-icon-plus" style="margin-right: 10px"></span>添加歌手</div>
        </div>
        <!-- 编辑歌手弹出框 -->
        <my-dialog :show="editSingerDialogVisible">
          <div class="editTitle" slot="title">
            <div class="title-text">编辑歌手信息:</div>
          </div>
          <div class="editInfo-container">
            <div class="editInfo-container-item uploadImg">
              <div class="uploadImg-title">歌手照片:</div>
              <div class="uploadImg-input-box no-img">
                <img :src="chooseImg" v-if="chooseImg" width="129" height="77" alt="" />
                <img src="@/assets/image/default-uploadImg.png" v-else width="51" height="51" alt="" />
              </div>
              <el-upload class="head-upload" name="testfile" :show-file-list="false" :http-request="handleFile" action>
                <div class="uploadImg-btn">
                  <el-button type="primary" size="small" icon="el-icon-circle-plus">选择图片</el-button>
                  <div class="tips">建议尺寸：900*500</div>
                </div>
              </el-upload>
            </div>
            <div class="editInfo-container-item award-info">
              <div class="title">歌手姓名:</div>
              <div class="input"><el-input v-model="singerName" placeholder="请输入歌手姓名"></el-input></div>
            </div>
          </div>
          <div class="editBtn-group">
            <el-button type="primary" class="save-btn" @click="editSinger">&nbsp;&nbsp;保存&nbsp;&nbsp;</el-button>
            <el-button type="info" class="cancel-btn" @click="cancelEdit">&nbsp;&nbsp;取消&nbsp;&nbsp;</el-button>
          </div>
        </my-dialog>
        <!-- 新增歌手弹出框 -->
        <my-dialog :show="addSingerDialogVisible">
          <div class="editTitle" slot="title">
            <div class="title-text">添加歌手:</div>
          </div>
          <div class="editInfo-container">
            <div class="editInfo-container-item uploadImg">
              <div class="uploadImg-title">歌手照片:</div>
              <div class="uploadImg-input-box no-img">
                <img :src="chooseImg" v-if="chooseImg" width="129" height="77" alt="" />
                <img src="@/assets/image/default-uploadImg.png" v-else width="51" height="51" alt="" />
              </div>
              <el-upload class="head-upload" name="testfile" :show-file-list="false" :http-request="handleFile" action>
                <div class="uploadImg-btn">
                  <el-button type="primary" size="small" icon="el-icon-circle-plus">选择图片</el-button>
                  <div class="tips">建议尺寸：900*500</div>
                </div>
              </el-upload>
            </div>
            <div class="editInfo-container-item award-info">
              <div class="title">歌手姓名:</div>
              <div class="input"><el-input v-model="singerName" placeholder="请输入歌手姓名"></el-input></div>
            </div>
          </div>
          <div class="editBtn-group">
            <el-button type="primary" class="save-btn" @click="addSinger">&nbsp;&nbsp;保存&nbsp;&nbsp;</el-button>
            <el-button type="info" class="cancel-btn" @click="cancelAdd">&nbsp;&nbsp;取消&nbsp;&nbsp;</el-button>
          </div>
        </my-dialog>
        <!-- 绑定微信弹出框 -->
        <my-dialog :show="bindWxDialogVisible" @close="closeBindWxDialog">
          <div class="editTitle" slot="title">
            <div class="title-text">绑定歌手微信</div>
          </div>
          <div class="bind-wx-container">
            <div class="phone-mockup">
              <div class="qrcode-wrapper">
                <img v-if="singerWxQrCode" :src="singerWxQrCode" alt="微信二维码" />
                <div v-else class="loading">加载中...</div>
              </div>
              <div class="tip-message">
                扫描二维码绑定歌手 {{ currentBindSinger ? currentBindSinger.name : '' }} 的微信
              </div>
            </div>
          </div>
          <div class="dialog-footer">
            <el-button @click="closeBindWxDialog">取消</el-button>
          </div>
        </my-dialog>
      </main-card>
    </div>
  </sub-page>
</template>
<script>
import SubPage from '@/components/subPage';
import MainCard from '@/components/mainCard';
import CardTopInfo from '@/components/cardTopInfo';
import MyTable from '@/components/myTable';
import { neidingLotteryList, lotteryListSetting, lotteryDelateOrEdit, getSingerBindWxQrCode, cancelSingerBindWx } from '@/api/setting/activitySetting/gameSetting';

import myDialog from '@/components/myDialog';
import request from '@/utils/request';

export default {
  name: 'awardSetting',
  data() {
    return {
      // 歌手列表
      singerList: [],
      addSingerDialogVisible: false,
      editSingerDialogVisible: false,
      // 绑定微信弹窗
      bindWxDialogVisible: false,
      currentBindSinger: null, // 当前要绑定的歌手
      singerWxQrCode: '', // 歌手微信绑定二维码
      bindPollingTimer: null, // 轮询定时器
      // 歌手照片
      chooseImg: '',
      // 歌手名称
      singerName: '',
      // 当前被编辑的歌手id
      currentSingerId: '',
    };
  },
  created() {
    this.requestSingerList();
  },
  components: {
    SubPage,
    MainCard,
    CardTopInfo,
    MyTable,
    myDialog,
  },
  methods: {
    // 获取歌手列表
    requestSingerList() {
      neidingLotteryList({
        splid: this.$store.state.liveId,
        gametype: '3',
        removed: '0',
        currentPage: '1',
        showCount: '500',
      }).then((res) => {
        console.log('singerList:', res.data.list);
        this.singerList = res.data.list;
      });
    },
    // 显示编辑歌手的弹框
    showEditSingerDialog(currentRow) {
      this.editSingerDialogVisible = true;
      this.chooseImg = currentRow.avator;
      this.singerName = currentRow.name;
      this.currentSingerId = currentRow.awardid;
    },
    // 显示增加歌手的弹框
    showAddSingerDialog() {
      this.addSingerDialogVisible = true;
    },
    // 新增歌手
    addSinger() {
      console.log(this.chooseImg, this.singerName);
      if (this.chooseImg && this.singerName) {
        lotteryListSetting({
          name: this.singerName,
          avator: this.chooseImg,
          gametype: '3',
          splid: this.$store.state.liveId,
          kind: '0', // 默认状态为不休息
        }).then((res) => {
          console.log('添加用户成功', res);
          this.$message({
            message: '添加用户成功',
            type: 'success',
          });
          this.requestSingerList();
        });
        this.clearData();
        this.addSingerDialogVisible = false;
      } else {
        this.$message({
          message: '请完善所有信息!',
          type: 'error',
        });
      }
    },
    // 编辑歌手
    editSinger() {
      if (this.chooseImg && this.singerName) {
        lotteryDelateOrEdit({
          awardid: this.currentSingerId,
          name: this.singerName,
          splid: this.$store.state.liveId,
          avator: this.chooseImg,
        }).then((res) => {
          console.log(res);
          if (res.code === 200) {
            this.$message({
              message: '修改歌手信息成功',
              type: 'success',
            });
            this.requestSingerList();
            this.clearData();
            this.editSingerDialogVisible = false;
          } else {
            this.$message({
              message: '修改歌手信息失败',
              type: 'error',
            });
          }
        });
      } else {
        this.$message({
          message: '请完善所有信息!',
          type: 'error',
        });
      }
    },
    // 取消编辑
    cancelEdit() {
      this.editSingerDialogVisible = false;
      this.clearData();
      console.log('取消编辑');
    },
    // 删除操作确认框
    confirmDelateOpen(id) {
      this.$confirm('此操作将永久删除该歌手, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          lotteryDelateOrEdit({
            splid: this.$store.state.liveId,
            awardid: id,
            removed: '1',
          }).then((res) => {
            if (res.code === 200) {
              console.log(res);
              this.$message({
                type: 'success',
                message: '删除成功!',
              });
              this.requestSingerList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    // 取消添加
    cancelAdd() {
      this.addSingerDialogVisible = false;
      this.clearData();
      console.log('取消添加');
    },
    /* 上传图片 */
    handleFile(e) {
      // 处理文件
      //  console.log(e)
      // 压缩一下文件

      const freader = new FileReader();
      freader.readAsDataURL(e.file); // 读取照片

      freader.onload = () => {
        this.chooseImg = freader.result;
        this.requestUploadFile();
      };
    },
    /* base 64 转换成file  这里对base64 进行压缩 */
    requestUploadFile() {
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      const img = new Image();
      img.src = this.chooseImg;
      // const that = this;
      img.onload = () => {
        canvas.width = img.width;
        canvas.height = img.height;
        context.clearRect(0, 0, img.width, img.height);
        context.drawImage(img, 0, 0, img.width, img.height);
        const result = canvas.toDataURL('image/jpeg', 0.7);

        // 转换成 file
        const formData = new FormData();
        const arr = result.split(',');
        // const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        const file = new File([u8arr], 'photo');
        formData.append('file', file);
        request
          .post('/beiJing/shangchuanTomcat', formData, { loading: 1 })
          .then((res) => {
            console.log(res);
            this.$message({
              message: '图片上传成功!',
              type: 'success',
            });
            this.chooseImg = res.data.filePath;
          })
          .catch((err) => {
            console.log(err);
            this.$message.error('图片上传失败!');
          });
      };
    },
    clearData() {
      this.chooseImg = '';
      this.singerName = '';
      this.currentSingerId = '';
    },
    // 显示绑定微信弹窗
    showBindWxDialog(singer) {
      this.currentBindSinger = singer;
      this.bindWxDialogVisible = true;
      this.getSingerWxQrCode();
    },
    // 获取歌手微信绑定二维码
    getSingerWxQrCode() {
      getSingerBindWxQrCode({
        singerId: this.currentBindSinger.awardid,
        splid: this.$store.state.liveId,
      })
        .then((res) => {
          this.singerWxQrCode = res;
          // 启动轮询检查绑定状态
          this.startBindPolling();
        })
        .catch((err) => {
          this.$message.error(`获取二维码失败: ${err}`);
        });
    },
    // 启动轮询检查绑定状态
    startBindPolling() {
      this.bindPollingTimer = setInterval(() => {
        this.checkBindStatus();
      }, 2000); // 每2秒检查一次
    },
    // 检查绑定状态
    checkBindStatus() {
      // 重新获取歌手列表,检查 singer_openId 是否有值
      neidingLotteryList({
        splid: this.$store.state.liveId,
        gametype: '3',
        removed: '0',
        currentPage: '1',
        showCount: '500',
      }).then((res) => {
        const singer = res.data.list.find(
          (s) => s.awardid === this.currentBindSinger.awardid,
        );

        if (singer && singer.singer_openId) {
          // 绑定成功
          this.stopBindPolling();
          this.closeBindWxDialog();
          this.$message.success('绑定成功');
          this.requestSingerList(); // 刷新列表
        }
      });
    },
    // 停止轮询
    stopBindPolling() {
      if (this.bindPollingTimer) {
        clearInterval(this.bindPollingTimer);
        this.bindPollingTimer = null;
      }
    },
    // 关闭绑定微信弹窗
    closeBindWxDialog() {
      this.stopBindPolling();
      this.bindWxDialogVisible = false;
      this.singerWxQrCode = '';
      this.currentBindSinger = null;
    },
    // 确认解绑
    confirmUnbindWx(singer) {
      this.$confirm(`确定要解除歌手"${singer.name}"的微信绑定吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.unbindSingerWx(singer);
        })
        .catch(() => {
          this.$message.info('已取消解绑');
        });
    },
    // 解绑歌手微信
    unbindSingerWx(singer) {
      cancelSingerBindWx({
        singerId: singer.awardid,
        splid: this.$store.state.liveId,
      })
        .then(() => {
          this.$message.success('解绑成功');
          this.requestSingerList(); // 刷新列表
        })
        .catch((err) => {
          this.$message.error(`解绑失败:${err}`);
        });
    },
    // 处理歌手状态变更
    handleSingerStatusChange(singer) {
      console.log('歌手状态变更:', singer);
      // 调用API更新歌手状态
      lotteryDelateOrEdit({
        awardid: singer.awardid,
        splid: this.$store.state.liveId,
        kind: singer.kind, // 添加kind字段
      }).then((res) => {
        console.log('状态更新结果:', res);
        if (res.code === 200) {
          this.$message({
            message: `歌手状态已${singer.kind === '1' ? '设为休息' : '设为不休息'}`,
            type: 'success',
          });
          // 刷新列表确保数据同步
          this.requestSingerList();
        } else {
          this.$message({
            message: '状态更新失败',
            type: 'error',
          });
          // 恢复原来的状态
          this.requestSingerList();
        }
      }).catch((err) => {
        console.error('状态更新失败:', err);
        this.$message.error('状态更新失败');
        // 恢复原来的状态
        this.requestSingerList();
      });
    },
  },
  beforeDestroy() {
    // 组件销毁时清理定时器
    this.stopBindPolling();
  },
};
</script>
<style lang="less" scoped>
.editTitle {
  display: flex;
  .title-text {
    font-size: 26px;
    font-family: SourceHanSansSC-Regular, SourceHanSansSC;
    font-weight: 400;
    color: #42474e;
  }
}
.editInfo-container {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  .editInfo-container-item {
    display: flex;
    align-items: center;
    margin-top: 30px;
  }
  .uploadImg {
    .uploadImg-input-box {
      width: 129px;
      height: 77px;
      border-radius: 4px;
      border: 1px dashed #cccccc;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 80px;
    }
    .uploadImg-btn {
      margin-left: 20px;
      .tips {
        margin-top: 10px;
        font-size: 11px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #333333;
      }
    }
  }
  .award-info {
    .title {
      font-size: 15px;
      font-family: SourceHanSansSC-Normal, SourceHanSansSC;
      font-weight: 400;
      color: #6f7682;
    }
    .input {
      margin-left: 80px;
    }
    .tips {
      font-size: 13px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #c7cdd5;
      margin-left: 20px;
    }
  }
}
.editBtn-group {
  padding-left: 143px;
  margin-top: 30px;
  margin-bottom: 40px;
  padding-bottom: 40px;
  .save-btn,
  .cancel-btn {
    padding: 10px 40px;
  }
  .cancel-btn {
    margin-left: 30px;
  }
}
.award-info-list-container {
  color: #1e87f0;
  .addAwardBtn {
    width: 96%;
    margin: 30px auto;
    height: 29px;
    border: 1px dashed #1e87f0;
    text-align: center;
    line-height: 29px;
    cursor: pointer;
  }
}
/* 绑定微信弹窗样式 */
.bind-wx-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;

  .phone-mockup {
    width: 287px;
    height: 542px;
    background-image: url('../../../assets/image/icon/userCenter/phone.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    margin-bottom: 20px;

    .qrcode-wrapper {
      margin-top: 81px;
      margin-bottom: 19px;
      position: relative;
      height: 200px;
      width: 200px;
      padding: 16px;
      background-color: #fff;

      img {
        width: 100%;
        height: 100%;
      }

      .loading {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        font-size: 16px;
        color: #666;
      }
    }

    .tip-message {
      text-align: center;
      letter-spacing: 1px;
      width: 221px;
      font-size: 16px;
      font-weight: 400;
      color: #ffffff;
      line-height: 32px;
    }
  }

  .dialog-footer {
    margin-top: 20px;
  }
}
</style>
